package auth

import (
	"context"

	v1 "gitee.com/liuxuezhan/ar-platform/rpc-client/authRoleClient/api/role/v1"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateRoleMenuInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUpdateRoleMenuInfoLogic 更新角色菜单权限（菜单应该通过权限操作赋权，且只能当前业务限制权限标识唯一才能使用，不希望调用该接口）
func NewUpdateRoleMenuInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRoleMenuInfoLogic {
	return &UpdateRoleMenuInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateRoleMenuInfoLogic) UpdateRoleMenuInfo(req *types.UpdateRoleMenuInfoRequest) error {
	// 修改角色信息
	_, err := l.svcCtx.AuthRoleRpc.UpdateRole(l.ctx, &v1.UpdateRoleRequest{
		Id:          req.RoleId,
		RolePid:     &req.RolePid,
		RoleName:    req.RoleName,
		Description: &req.Description,
		Remark:      &req.Remark,
		ListOrder:   &req.ListOrder,
		Status:      v1.Status(req.Status),
	})
	if err != nil {
		return err
	}

	// 获取菜单权限id
	menuPermissionIds, err := l.svcCtx.AuthRoleRpc.GetRolePermissionIds(l.ctx, &v1.GetRolePermissionIdsRequest{
		RoleId:               req.RoleId,
		PermissionIdentifier: PerIdentMenu,
	})
	if err != nil {
		return err
	}

	var permissionId int64
	// 如果当前用户没有权限则给他新增权限
	if len(menuPermissionIds.GetPermissionIds()) == 0 {
		// 创建权限
		permission, err := l.svcCtx.AuthRoleRpc.CreatePermission(l.ctx, &v1.CreatePermissionRequest{
			PermissionName:       req.RoleName + "-菜单权限",
			PermissionIdentifier: PerIdentMenu,
			Status:               v1.Status_StatusNormal,
		})
		if err != nil {
			return err
		}

		// 创建角色和权限的关联关系
		if _, err = l.svcCtx.AuthRoleRpc.UpdateRolePermissions(l.ctx, &v1.UpdateRolePermissionsRequest{
			RoleId:        req.RoleId,
			PermissionIds: []int64{permission.Id},
		}); err != nil {
			return err
		}

		permissionId = permission.GetId()
	} else {
		permissionId = menuPermissionIds.GetPermissionIds()[0]
	}

	// 修改菜单权限
	_, err = l.svcCtx.AuthRoleRpc.UpdatePermissionFunctions(l.ctx, &v1.UpdatePermissionFunctionsRequest{
		PermissionId: permissionId,
		FunctionIds:  req.MenuIds,
	})
	if err != nil {
		return err
	}

	return nil
}
